using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;

namespace CommonTagTime
{
    public class clsEmail
    {
        //------------------------------------------------
        //PROPERTY
        //------------------------------------------------
        public string BCC
        {
            get
            {
                return this._BCC;
            }
            set
            {
                this._BCC = value;
            }
        }

        public string Body
        {
            get
            {
                return this._Body;
            }
            set
            {
                this._Body = value;
            }
        }

        public enmBodyFormat BodyFormat
        {
            get
            {
                return this._BodyFormat;
            }
            set
            {
                this._BodyFormat = value;
            }
        }

        public string CC
        {
            get
            {
                return this._CC;
            }
            set
            {
                this._CC = value;
            }
        }

        public string Receiver
        {
            get
            {
                return this._Receiver;
            }
            set
            {
                this._Receiver = value;
            }
        }

        public string Sender
        {
            get
            {
                return this._Sender;
            }
            set
            {
                this._Sender = value;
            }
        }
        
        public string SenderName
        {
            get
            {
                return this._SenderName;
            }
            set
            {
                this._SenderName = value;
            }
        }

        public string Server
        {
            get
            {
                return this._Server;
            }
            set
            {
                this._Server = value;
            }
        }

        public string Subject
        {
            get
            {
                return this._Subject;
            }
            set
            {
                this._Subject = value;
            }
        }
        public int TimeOut
        {
            get
            {
                return this._TimeOut;
            }
            set
            {
                this._TimeOut = value;
            }
        }

        //------------------------------------------------
        //VARIABLE
        //------------------------------------------------
        private string[] _AttachedFiles;
        private string _BCC;
        private string _Body;
        private enmBodyFormat _BodyFormat;
        private string _CC;
        private string _Receiver;
        private string _Sender;
        private string _SenderName;
        private string _Server;
        private string _Subject;
        private int _TimeOut;
        //------------------------------------------------
        //PRIVATE
        //------------------------------------------------
        public clsEmail()
        {
            this._AttachedFiles = new string[0];
            this._Init();
        }

        private bool _EmailError(string _Function, string _Message)
        {
            try
            {
                this.Sender = ConfigurationManager.AppSettings["MasterEmail"];
                this.Receiver = ConfigurationManager.AppSettings["MasterEmail"];
                this.Subject = string.Format("[CommonTagTime] BUG", new object[0]);
                this.BodyFormat = enmBodyFormat.HTML;
                this.Body = string.Format("URL: {0} <br>FUNCTION: {1}<br>{2} <br><br>MESSAGE: {3} <br><br>ON: {4} ", HttpContext.Current.Request.Url.ToString(), HttpContext.Current.Request.RawUrl.ToString(), _Function, _Message, DateTime.Now);
                this.Send();
                return true;
            }
            catch (Exception)
            {
                clsFile.WriteLog("clsEmail", "_EmailError", string.Format(@"Cannot send email bug website. Please contact email {0} to support!", this.Receiver));
                return false;
            }
        }

        private void _Init()
        {
            this._Sender = string.Empty;
            this._SenderName = string.Empty;
            this._Receiver = string.Empty;
            this._CC = string.Empty;
            this._BCC = string.Empty;
            this._Subject = string.Empty;
            this._Body = string.Empty;
            this._AttachedFiles = new string[0];
            this._Server = ConfigurationManager.AppSettings["EmailServer"];
            this._BodyFormat = enmBodyFormat.HTML;
            this._TimeOut = 1000;
        }

        private bool _IsAttachedFilesExist(string[] arr)
        {
            string strNotExistFiles = "";
            if (arr.Length == 0)
            {
                return true;
            }
            for (int i = 0; i <= (arr.Length - 1); i++)
            {
                if (!((arr[i] != "") && this._IsFileExist(arr[i])))
                {
                    strNotExistFiles = strNotExistFiles + ((strNotExistFiles == "") ? "" : ", ") + arr[i];
                }
            }
            if (strNotExistFiles == "")
            {
                return true;
            }
            return false;
        }

        private bool _IsFileExist(string FilePath)
        {
            try
            {
                return System.IO.File.Exists(FilePath);
            }
            catch (Exception)
            {
                return false;
            }
        }

        private bool _Send()
        {
            bool flag = false;
            if ((((this._Server != "") && (this._Sender != "")) && ((this._Receiver != "") && (this._Subject != ""))) && (this._Body != ""))
            {
                MailMessage mail = new MailMessage();

                mail.From = new MailAddress(this._Sender, this._SenderName);

                // Add by: Lan Pham 13/12/2007
                this._Receiver = this._Receiver.Replace(',', ';');
                string[] _arrReceiver = this._Receiver.Split(';');

                for (int i=0; i<_arrReceiver.Length; i++)
                {
                    mail.To.Add(_arrReceiver[i]);
                }
                // end

                if (this._CC != "")
                {
                    mail.CC.Add(this._CC);
                }
                if (this._BCC != "")
                {
                    mail.Bcc.Add(this._BCC);
                }
                if (this._AttachedFiles.Length > 0)
                {
                    for (int i = 0; i <= (this._AttachedFiles.Length - 1); i++)
                    {
                        Attachment data = new Attachment(this._AttachedFiles[i]);
                        mail.Attachments.Add(data);
                    }
                }
                if (this._BodyFormat == enmBodyFormat.HTML)
                {
                    mail.IsBodyHtml = true;
                }
                else
                {
                    mail.IsBodyHtml = false;
                }
                mail.Subject = this._Subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Body = this._Body;
                mail.BodyEncoding = Encoding.UTF8;
                try
                {
                    SmtpClient server = new SmtpClient();
                    server.Host = this._Server;
                    server.Port = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);
                    server.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUsername"], ConfigurationManager.AppSettings["EmailPassword"]);
                    server.EnableSsl = true;
                    server.Send(mail);
                    flag = true;
                }
                catch (Exception ex)
                {
                    clsFile.WriteLog("clsEmail", "_Send", ex.ToString());
                }
                finally
                {
                    mail.Dispose();
                }
            }
            return flag;
        }

        //------------------------------------------------
        //PUBLIC
        //------------------------------------------------
        public string AttachedFiles(byte index)
        {
            if (index < this._AttachedFiles.Length)
            {
                return this._AttachedFiles[index];
            }

            return "";
        }

        public bool EmailError(string _Function, string _Message)
        {
            return this._EmailError(_Function, _Message);
        }

        public bool Send()
        {
                return this._Send();
        }

        public void SetAttachedFiles(byte index, string Value)
        {
            if (this._IsFileExist(Value))
            {
                if (index < this._AttachedFiles.Length)
                {
                    this._AttachedFiles[index] = Value;
                }
                else if (index == this._AttachedFiles.Length)
                {
                    this._AttachedFiles = new string[(index + 1) + 1];
                    this._AttachedFiles[index] = Value;
                }
                else
                {
                    HttpContext.Current.Response.Write("clsEmail - SetAttachedFiles");
                }
            }
            else
            {
                if (index < this._AttachedFiles.Length)
                {
                    this._AttachedFiles[index] = "";
                }
            }
        }
        public bool SendExchangeMail()
        {
            bool flag = false;
            if ((((this._Server != "") && (this._Sender != "")) && ((this._Receiver != "") && (this._Subject != ""))) && (this._Body != "") && this._TimeOut>0)
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(this._Sender, this._SenderName);              
                this._Receiver = this._Receiver.Replace(',', ';');
                string[] _arrReceiver = this._Receiver.Split(';');
                for (int i = 0; i < _arrReceiver.Length; i++)
                {
                    mail.To.Add(_arrReceiver[i]);
                }
                if (this._CC != "")
                {
                    mail.CC.Add(this._CC);
                }
                if (this._BCC != "")
                {
                    mail.Bcc.Add(this._BCC);
                }
                if (this._AttachedFiles.Length > 0)
                {
                    for (int i = 0; i <= (this._AttachedFiles.Length - 1); i++)
                    {
                        Attachment data = new Attachment(this._AttachedFiles[i]);
                        mail.Attachments.Add(data);
                    }
                }
                if (this._BodyFormat == enmBodyFormat.HTML)
                {
                    mail.IsBodyHtml = true;
                }
                else
                {
                    mail.IsBodyHtml = false;
                }
                mail.Subject = this._Subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Body = this._Body;
                mail.BodyEncoding = Encoding.UTF8;
                try
                {
                    SmtpClient server = new SmtpClient();
                    server.Host = this._Server;
                    server.Timeout = this._TimeOut;                 
                    server.Send(mail);
                    flag = true;
                }
                catch (Exception ex)
                {
                    clsFile.WriteLog("clsEmail", "_Send", ex.ToString());
                }
                finally
                {
                    mail.Dispose();
                }
            }
            return flag;
        }
    }
}

